package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DrugDTO;
import com.sky.dto.DrugPageQueryDTO;
import com.sky.entity.Drug;
import com.sky.exception.BusinessException;
import com.sky.mapper.DrugMapper;
import com.sky.result.PageResult;
import com.sky.service.DrugService;
import com.sky.vo.DrugDetailVO;
import com.sky.vo.DrugVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DrugServiceImpl implements DrugService {
    @Autowired
    private DrugMapper drugMapper;
    /**
     * 查询药品列表
     *
     * @return
     */
    @Override
    public PageResult list(DrugPageQueryDTO queryDTO) {
        Long userId = BaseContext.getCurrentId();
        PageResult pageResult = new PageResult();
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Drug> page = (Page<Drug>) drugMapper.listByUserId(userId);
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        log.info("我的pageReslut:{}", pageResult);
        return pageResult;

    }

    @Override
    public DrugDetailVO detail(Long id) {
        Drug drug = drugMapper.selectById(id);
        if (drug == null || drug.getUserId() == null || !drug.getUserId().equals(BaseContext.getCurrentId())) {
            throw new BusinessException(MessageConstant.QUERY_FAIL);
        }
        DrugDetailVO drugDetailVO = new DrugDetailVO();
        BeanUtils.copyProperties(drug, drugDetailVO);
        return drugDetailVO;
    }

    @Override
    public void add(DrugDTO drugDTO) {
        Drug drug = new Drug();
        Long userId = BaseContext.getCurrentId();
        drug.setUserId(userId);
        BeanUtils.copyProperties(drugDTO, drug);
        drugMapper.insert(drug);
    }

    @Override
    public void delete(Long id) {
        Drug drug = drugMapper.selectById(id);
        // 查不到药品或删除人不是药品拥有者, 不能删除
        if (drug == null || drug.getUserId() == null || !drug.getUserId().equals(BaseContext.getCurrentId())) {
            throw new BusinessException(MessageConstant.DELETE_FAIL);
        }
        drugMapper.deleteById(id);
    }

    /**
     * 修改药品信息
     *
     * @param drugDTO
     */
    @Override
    public void update(DrugDTO drugDTO) {
        Drug drug = drugMapper.selectById(drugDTO.getId());
        // 查不到药品或删除人不是药品拥有者, 不能修改
        if (drug == null || drug.getUserId() == null || !drug.getUserId().equals(BaseContext.getCurrentId())) {
            throw new BusinessException(MessageConstant.UPDATE_FAIL);
        }
        BeanUtils.copyProperties(drugDTO, drug);
        drugMapper.update(drug);
    }
}
